<?php
/**
 * SystemText Model
 *
 * Utilizes the Data Mapper pattern to persist data. Represents a single
 * system_text entry
 *
 * @version $Id: SystemText.php 105 2010-05-11 05:52:35Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Default_Model_SystemTextMapper
 * @package default
 * @subpackage Model
 */
class Default_Model_SystemText extends Default_Model_Doctrine_BaseSystemText
{
    const HAS_EMPTY_OPTION = 1;

    protected $_groups = array("student","score","system");

    protected function _getTextByGroup($group_id)
    {
        $q = $this->getTable()->createQuery('a')
        ->select('sn AS id, name AS text')
        ->where('group_id=?', $group_id)
        ->andWhere('parent_sn=0')
        ->orderBy('sort');
        $res = $q->fetchArray();

        $arr = array();
        foreach ($res as $row) {
            $q = $this->getTable()->createQuery('a')
            ->select('COUNT(*) AS cc')
            ->where('parent_sn=?', $row['id']);
            $res2 = $q->fetchOne();
            if ($res2) {
                if ($res2->cc > 0)
                $row['hasChildren'] = true;
            }
            $arr[] = $row;
        }
        return $arr;
    }


    /**
     *  主選單
     * @return array
     */
    public function getRoot()
    {
        $arr = array();
        foreach ($this->_groups as $val) {
            $arr2 = array();
            $arr2['text'] = $val;
            $arr2['children'] = $this->_getTextByGroup($val);
            $arr[] = $arr2;
        }
        return $arr;
    }

    /**
     *  次選單
     * @param $sn
     * @return array
     */
    public function getChildrens($sn)
    {
        return  $this->getTable()->createQuery('a')
        ->where('parent_sn=?',$sn)->orderBy('sort')->fetchArray();
    }

    /**
     *  下拉選單陣列
     * @param $name
     * @param $has_empty_option
     * @return unknown_type
     */
    public function getKindArray($name,$has_empty_option=0)
    {
        $res = $this->getTable()->createQuery('a')
        ->where("kind=?",$name)
        ->andWhere('parent_sn<>0')
        ->fetchArray();
        $arr = array();
        foreach($res as $row)
        $arr[$row['id']] = $row['name'];

        if ($has_empty_option)
        $arr = array_merge(array(""),$arr);

        return $arr;
    }
}
